import { Table } from "antd";
import axios from "axios";
import React, { useEffect } from "react";

export default function TableDynamicField() {
    const [data, setData] = React.useState<any[]>([]);
    useEffect(() => {
        getData();
    },[])
    const getData = async () => {
        axios.get("http://localhost:8000/api/dataListDynamic").then((res) => {
            setData(res.data.data.list);
        })
    }
    // 从数据中提取所有的字段名称
    const columns = data
        .reduce<string[]>((acc, current) => {
            Object.keys(current).forEach((key) => {
                if (!acc.includes(key) && current[key] !== null) {
                    acc.push(key);
                }
            });
            return acc;
        }, [])
        .sort();
    const tableColumns = columns.map((column: any) => ({
        title: column,
        dataIndex: column,
        key: column,
        render: (text: any) => <a>{text}</a>,
    }));
    return (
        <div>
            <h1>TableDynamicField</h1>
            <button className="returnButton">
                <a href="/">点击返回主菜单</a>
            </button>
            <p>
                本demo需要启动服务器，该demo实现了获取接口数据，根据接口数据动态选择表格字段。
            </p>
            <Table dataSource={data} columns={tableColumns} />
        </div>
    );
}

// 根据字段名称生成表格列

// return (
// <div>
// pagination={{
// total: totalNum,
// pageSizeOptions: [5, 10, 20, 50, 100],
// onChange: changePagination,
// showTotal: (total) => `共${total}条记录 `,
// position: ["bottomRight"],
// showSizeChanger: true,
// showQuickJumper: true,
// }}
// </div>
// );
// }
